﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace BarStructures.Deformed
{
    public class FrameDeformedState: DeformedState
    {
        private Model model = null;

        private BoundingBox cachedBBox = null;

        public override void AssignToModel(Model model)
        {
            this.model = model;
        }

        public override BoundingBox GetModelEnvelope()
        {
            //if (cachedBBox == null)
            {
                NodeDisplacement nodeDisplacement = this[0];
                double x, y;
                x = nodeDisplacement.Node.X + nodeDisplacement.Dx;
                y = nodeDisplacement.Node.Y + nodeDisplacement.Dy;
                BoundingBox deformedBBox = new BoundingBox(x, y, x, y);
                int nodesCount = model.GetNodesCount();
                for (int i = 1; i < nodesCount; i++)
                {
                    nodeDisplacement = this[i];
                    x = nodeDisplacement.Node.X + nodeDisplacement.Dx;
                    y = nodeDisplacement.Node.Y + nodeDisplacement.Dy;

                    if (deformedBBox.MinX > x)
                        deformedBBox.MinX = x;
                    else if (deformedBBox.MaxX < x)
                        deformedBBox.MaxX = x;

                    if (deformedBBox.MinY > y)
                        deformedBBox.MinY = y;
                    else if (deformedBBox.MaxY < y)
                        deformedBBox.MaxY = y;
                }

                BoundingBox orgBBox = model.GetModelEnvelope();

                cachedBBox = new BoundingBox(Math.Min(orgBBox.MinX, deformedBBox.MinX),
                                             Math.Min(orgBBox.MinY, deformedBBox.MinY),
                                             Math.Max(orgBBox.MaxX, deformedBBox.MaxX),
                                             Math.Max(orgBBox.MaxY, deformedBBox.MaxY));
            }
            return cachedBBox;
        }

        public override void Draw(IDrawBoard d)
        {
            model.Draw(d);

            //отрисовка деформированного состояния
            NodeDisplacement nodeDisplacement;
            int nodesCount = model.GetNodesCount();
            for (int i = 0; i < nodesCount; i++)
            {
                nodeDisplacement = this[i];
                nodeDisplacement.Node.Draw(d, nodeDisplacement, _Scale);
            }

            Bar bar;
            int barsCount = model.GetBarsCount();
            for (int i = 0; i < barsCount; i++)
            {
                bar = model.GetBar(i);
                bar.Draw(d, this[bar.NodeOne.SystemIndex], this[bar.NodeTwo.SystemIndex], model.DrawAsFrame, _Scale);
            }
        }
    }
}
